﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using log4net;
using Portal.Presentation.Controllers;

namespace Portal.Presentation
{
	public class ApplicationError
	{
		#region Fields
		private static readonly ILog _logger; 
		#endregion

		#region .ctor
		/// <summary>
		/// Initializes the <see cref="ApplicationError"/> class.
		/// </summary>
		static ApplicationError()
		{
			_logger = LogManager.GetLogger("Portal");
		} 
		#endregion

		#region Methods
		/// <summary>
		/// Raises the specified error.
		/// </summary>
		/// <param name="context">The context.</param>
		/// <param name="ex">The ex.</param>
		internal static void Raise(HttpContext context, Exception ex)
		{
			var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context));
			var currentController = " ";
			var currentAction = " ";

			if (currentRouteData != null)
			{
				if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
				{
					currentController = currentRouteData.Values["controller"].ToString();
				}

				if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
				{
					currentAction = currentRouteData.Values["action"].ToString();
				}
			}

			var controller = new ErrorController();
			var routeData = new RouteData();
			var action = "General";

			if (ex is HttpException)
			{
				var httpException = ex as HttpException;

				switch (httpException.GetHttpCode())
				{
					case 404:
						// page not found
						action = "HttpError404";
						break;
					case 500:
						// server error
						action = "HttpError500";
						break;
					// others if any

					default:
						action = "General";
						break;
				}
			}

			context.ClearError();
			context.Response.Clear();
			context.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
			context.Response.TrySkipIisCustomErrors = true;
			routeData.Values["controller"] = "Error";
			routeData.Values["action"] = action;
			routeData.Values["ex"] = ex;

			_logger.Error(ex.Message, ex);

			controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
			((IController)controller).Execute(new RequestContext(new HttpContextWrapper(context), routeData));
		} 
		#endregion

		
	}
}